package com.example.demo.controller;

import com.example.demo.model.UserInfo;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-01-13
 * Time: 17:59
 */

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    //JDBC事务管理器
    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;
    //定义事务属性
    @Autowired
    private TransactionDefinition transactionDefinition;

    @RequestMapping("/getall")
    public List<UserInfo> getAll() {
        System.out.println("执行了getall方法");
        return userService.getAll();
    }

    @RequestMapping("/getuserinfo")
    public int getUserInfo(String username,String password) {
        //进行非空校验
        if(!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return 0;
        }
        //开启事务
        TransactionStatus transaction = dataSourceTransactionManager.getTransaction(transactionDefinition);
        //插入数据库
        int res = userService.getUserInfo(username, password);
        //提交事务
        //dataSourceTransactionManager.commit(transaction);
        //回滚事务
        dataSourceTransactionManager.commit(transaction);
        return res;
    }

    @RequestMapping("/getuserinfo1")
    @Transactional
    public int getUserInfo1(String username,String password) {
        //进行非空校验
        if(!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return 0;
        }
        //插入数据库
        int res = userService.getUserInfo(username, password);
        System.out.println("受影响的行数 : "+ res);
        try{
            int x = 10/0;
        }catch (Exception e) {
            System.out.println("当前程序发生异常,手动回滚事务" +
                    e.getMessage());
            //手动回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return res;
    }
}